package com.working.libcommon.util

import android.content.Context
import android.net.*
import androidx.lifecycle.MutableLiveData

enum class NetworkStatus {
    NONE, WIFI, CELLULAR, OTHER
}

object NetworkStatusMonitor {

    val netEvent = MutableLiveData<NetworkStatus>()


    fun inject(context: Context) {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val builder = NetworkRequest.Builder()
        val request = builder.build()
        connectivityManager.registerNetworkCallback(request, object :
            ConnectivityManager.NetworkCallback() {

            override fun onCapabilitiesChanged(
                network: Network,
                networkCapabilities: NetworkCapabilities
            ) {
                if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
                    when {
                        networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                            netEvent.postValue(NetworkStatus.WIFI)
                        }
                        networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                            netEvent.postValue(NetworkStatus.CELLULAR)
                        }
                        else -> {
                            netEvent.postValue(NetworkStatus.OTHER)
                        }
                    }
                }

            }

            override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
                super.onLinkPropertiesChanged(network, linkProperties)
            }
            override fun onLost(network: Network) {
                netEvent.postValue(NetworkStatus.NONE)
            }
        })

    }
}